package com.handinfo.android.game;

import java.io.DataInputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Point;

import com.handinfo.android.DWGameManager;
import com.handinfo.android.core.graphics.DWFont;
import com.handinfo.android.core.graphics.DWGraphics;
import com.handinfo.android.core.object.Actor;
import com.handinfo.android.core.object.Animation;
import com.handinfo.android.core.object.Scene;
import com.handinfo.android.core.resource.DWSerializableFactory;
import com.handinfo.android.core.resource.ResHead;
import com.handinfo.android.core.resource.Resource;
import com.handinfo.android.core.resource.ResourceManager;
import com.handinfo.android.game.skill.SkillConstants;
import com.handinfo.android.ui.UIWindows;
import com.handinfo.android.ui.window.UIHook;
import com.handinfo.android.uicontrols.DWControlsManager;
import com.handinfo.android.uicontrols.DWListener;
import com.handinfo.android.uicontrols.controls.DWMessageBox;
import com.handinfo.android.utils.Tools;

/**
 * 
 * NPC
 * 
 * @author mujianchen
 * 
 */

public class Npc extends GameActor
{
//	public int m_head_state = 0;// NPC头上状态
	public byte m_function_icon = -1;//NPC功能图标
	public String m_head_tips = null;//NPC头上状态提示
	public static Bitmap[] s_img_head_status = null;// NPC头上图标
	public static Bitmap[] s_img_head_funcs = null;//
	public Npc()
	{
		super();
	}

	public Npc(Resource resource)
	{
		super(resource);
	}
	
	public static void initStaticResource()
	{
		// NPC头上状态图标
		if (s_img_head_status == null) {
			s_img_head_status = new Bitmap[Npc.IMG_HS_AMOUNT];
			s_img_head_status[Npc.IMG_HS_Y_QUESTION_MARK] = UIWindows.createImage("/img/newui/hw.gnp");
			s_img_head_status[Npc.IMG_HS_B_QUESTION_MARK] = UIWindows.createImage("/img/newui/lw.gnp");
			s_img_head_status[Npc.IMG_HS_Y_EXCLAMATION_MARK] = UIWindows.createImage("/img/newui/hg.gnp");
			s_img_head_status[Npc.IMG_HS_B_EXCLAMATION_MARK] = UIWindows.createImage("/img/newui/lg.gnp");
			s_img_head_status[Npc.IMG_HS_G_QUESTION_MARK] = UIWindows.createImage("/img/newui/hhw.gnp");
		}
		if(s_img_head_funcs == null){
			s_img_head_funcs = new Bitmap[Npc.IMG_FC_AMOUNT];
			s_img_head_funcs[Npc.IMG_FC_SHOP] = UIWindows.createImage("/img/newui/npcshang_1.gnp");
			s_img_head_funcs[Npc.IMG_FC_REPAIR] = UIWindows.createImage("/img/newui/npcxiu_1.gnp");
			s_img_head_funcs[Npc.IMG_FC_LIBAO] = UIWindows.createImage("/img/newui/npcli_1.gnp");
			s_img_head_funcs[Npc.IMG_FC_MEIRI] = UIWindows.createImage("/img/newui/npcmei_1.gnp");
			s_img_head_funcs[Npc.IMG_FC_JIHUN] = UIWindows.createImage("/img/newui/npchun_1.gnp");
			s_img_head_funcs[Npc.IMG_FC_CANGKU] = UIWindows.createImage("/img/newui/npcku_1.gnp");
			s_img_head_funcs[Npc.IMG_FC_ZHANGHAO] = UIWindows.createImage("/img/newui/npchao_1.gnp");	
			s_img_head_funcs[Npc.IMG_FC_JI] = UIWindows.createImage("/img/newui/npcji_1.gnp");
			s_img_head_funcs[Npc.IMG_FC_TAN] = UIWindows.createImage("/img/newui/npctan_1.gnp");
		}
	}

	/**
	 * 关联Actor的ID
	 * 道具：用于存储道具归属的Role的IDs
	 */
	public long[] m_relatedActorsID;

	public Actor clone(Actor actor)
	{
		Npc ca = new Npc();

		ca.m_scene = actor.m_scene;
		ca.m_anims = new Animation[actor.m_anims.length];
		System.arraycopy(actor.m_anims, 0, ca.m_anims, 0, actor.m_anims.length);
		ca.m_anim = actor.m_anim;
		ca.m_actionIDNow = actor.m_actionIDNow;
		ca.m_actionIDBefore = actor.m_actionIDBefore;
		ca.m_frameId = actor.m_frameId;
		ca.m_frameIndex = actor.m_frameIndex;
		ca.m_frameDuration = actor.m_frameDuration;
		ca.m_actionCycle = actor.m_actionCycle;
		ca.m_actionOver = actor.m_actionOver;
		ca.m_layer = actor.m_layer;
		ca.m_phyLayer = actor.m_phyLayer;
		ca.m_flag = actor.m_flag;
		ca.m_flipX = actor.m_flipX;
		ca.m_flipY = actor.m_flipY;
		ca.m_visible = actor.m_visible;
		ca.m_enabled = actor.m_enabled;
		ca.m_needDraw = actor.m_needDraw;
		ca.m_posX = actor.m_posX;
		ca.m_posY = actor.m_posY;
		ca.m_vX = actor.m_vX;
		ca.m_vY = actor.m_vY;
		ca.m_collideBox = new short[actor.m_collideBox.length];
		System.arraycopy(actor.m_collideBox, 0, ca.m_collideBox, 0,
				actor.m_collideBox.length);
		ca.m_activeBox = new short[actor.m_activeBox.length];
		System.arraycopy(actor.m_activeBox, 0, ca.m_activeBox, 0,
				actor.m_activeBox.length);
		ca.m_parameters = new short[actor.m_parameters.length];
		System.arraycopy(actor.m_parameters, 0, ca.m_parameters, 0,
				actor.m_parameters.length);
		return ca;
	}

	/** 不显示 */
	public static final byte HEAD_STATE_NONE = 0;
	/** 黄问号 */
	public static final byte HEAD_STATE_YELLOW_QUESTION_MARK = 1;
	/** 蓝问号 */
	public static final byte HEAD_STATE_BLUE_QUESTION_MARK = 2;
	/** 黄叹号 */
	public static final byte HEAD_STATE_YELLOW_EXCLAMATION_MARK = 4;
	/** 蓝叹号 */
	public static final byte HEAD_STATE_BLUE_EXCLAMATION_MARK = 8;
	/** 灰问号 */
	public static final byte HEAD_STATE_GRAY_QUESTION_MARK = 16;

	public static final byte IMG_HS_Y_QUESTION_MARK = 0;
	public static final byte IMG_HS_B_QUESTION_MARK = 1;
	public static final byte IMG_HS_Y_EXCLAMATION_MARK = 2;
	public static final byte IMG_HS_B_EXCLAMATION_MARK = 3;
	public static final byte IMG_HS_G_QUESTION_MARK = 4;
	public static final byte IMG_HS_AMOUNT = 5;
	public static final byte IMG_FC_SHOP = 0;
	public static final byte IMG_FC_REPAIR = 1;
	public static final byte IMG_FC_LIBAO = 2;
	public static final byte IMG_FC_MEIRI = 3;
	public static final byte IMG_FC_JIHUN = 4;
	public static final byte IMG_FC_CANGKU = 5;
	public static final byte IMG_FC_ZHANGHAO = 6;
	public static final byte IMG_FC_JI = 7;
	public static final byte IMG_FC_TAN = 8;
	public static final byte IMG_FC_AMOUNT = 9;

	public synchronized void draw(DWGraphics g, int camX, int camY)
	{
		switch (m_actionIDNow / DIRECT_NUM) {
			case ACTION_DEAD:
				break;
			default:
				g.setClip(0, 0, DWGameManager.Screen_Width,
						DWGameManager.Screen_Height);
				g.setColor(GameActorConstants.COLOR_ACTOR_SHADOW);
				g.fillArc(m_posX - camX + m_collideBox[0], m_posY - camY + m_collideBox[1],
						m_collideBox[2] - m_collideBox[0], m_collideBox[3] - m_collideBox[1],
						0, 360);
				break;
		}
		if (m_scene != null) {
			if (this == ((Scene) m_scene).m_controlledActor.m_targetActor) {
				Scene.s_targetFrame.m_posX = m_posX;
				Scene.s_targetFrame.m_posY = m_posY;
				Scene.s_targetFrame.draw(g, camX, camY);
				Scene.s_targetFrame.nextFrame();
			}
		}
		super.draw(g, camX, camY);
		g.setClip(0, 0, DWGameManager.Screen_Width, DWGameManager.Screen_Height);
		if (m_name != null) {
			if(m_type == GameActorConstants.ACTOR_TYPE_PET){
				if (m_status != ACTOR_STATUS_DEAD) {
					g.drawShadowString(m_name, Tools.BLACK, Tools.YELLOW, m_posX - camX, m_posY - camY + m_activeBox[1], Tools.HCENTER_BOTTOM);
				}
				return;
			}
			switch (m_head_state) {
				case HEAD_STATE_YELLOW_QUESTION_MARK:// 1黄问号
					g.drawBitmap(s_img_head_status[IMG_HS_Y_QUESTION_MARK],
							m_posX - camX, m_posY - camY + m_activeBox[1] - 20, Tools.HCENTER_BOTTOM);
					break;
				case HEAD_STATE_BLUE_QUESTION_MARK:// 2蓝问号
					g.drawBitmap(s_img_head_status[IMG_HS_B_QUESTION_MARK],
							m_posX - camX, m_posY - camY + m_activeBox[1] - 20, Tools.HCENTER_BOTTOM);
					break;
				case HEAD_STATE_YELLOW_EXCLAMATION_MARK:// 4黄叹号
					g.drawBitmap(s_img_head_status[IMG_HS_Y_EXCLAMATION_MARK],
							m_posX - camX, m_posY - camY + m_activeBox[1] -20, Tools.HCENTER_BOTTOM);
					break;
				case HEAD_STATE_BLUE_EXCLAMATION_MARK:// 8蓝叹号
					g.drawBitmap(s_img_head_status[IMG_HS_B_EXCLAMATION_MARK],
							m_posX - camX, m_posY - camY + m_activeBox[1] - 20, Tools.HCENTER_BOTTOM);
					break;
				case HEAD_STATE_GRAY_QUESTION_MARK:// 16灰问号
					g.drawBitmap(s_img_head_status[IMG_HS_G_QUESTION_MARK],
							m_posX - camX, m_posY - camY + m_activeBox[1] - 20, Tools.HCENTER_BOTTOM);
					break;
			}
			if(m_function_icon > 0 && m_function_icon <= Npc.IMG_FC_AMOUNT){
				if(s_img_head_funcs[m_function_icon - 1] != null){
					float fc_w = ((int)(DWFont.getDefaultFont().stringWidth(m_name))>> 1)+(s_img_head_funcs[m_function_icon - 1].getWidth() >> 1)+1;
					g.drawBitmap(s_img_head_funcs[m_function_icon - 1],
							m_posX - camX - fc_w, m_posY - camY + m_activeBox[1], Tools.HCENTER_BOTTOM);
				}
			}
			
			if ((m_actor_flag & GameActorConstants.ACTOR_FLAG_FIGHT) != 0) {
				if (m_status != ACTOR_STATUS_DEAD) {
					g.drawShadowString(m_name, Tools.BLACK, Tools.RED, m_posX - camX, m_posY - camY + m_activeBox[1], Tools.HCENTER_BOTTOM);
				}
			}
			else {
				if (m_status != ACTOR_STATUS_DEAD) {
					g.drawShadowString(m_name, Tools.BLACK, Tools.YELLOW, m_posX - camX, m_posY - camY + m_activeBox[1], Tools.HCENTER_BOTTOM);
				}
			}
			
			if( m_type == GameActorConstants.ACTOR_TYPE_NPC
					&& m_scene.m_controlledActor != null 
					&& m_scene.m_controlledActor.m_targetActor != null
					&& this == m_scene.m_controlledActor.m_targetActor
					&& m_status != ACTOR_STATUS_DEAD){
				g.drawShadowString(m_head_tips, Tools.BLACK, Tools.ORANGE, m_posX - camX, m_posY - camY + m_activeBox[1]-g.getFontHeight()-3, Tools.HCENTER_BOTTOM);
			}
//			if (m_type == GameActorConstants.ACTOR_TYPE_NPC) {
//				if (m_status != ACTOR_STATUS_DEAD) {
//					if (m_faction == FACTION_FRIEND || m_faction == DWGameManager.getInstance().m_role.m_faction) {
//						g.drawShadowString(m_name, Tools.BLACK, Tools.YELLOW, m_posX - camX, m_posY - camY + m_activeBox[1], Tools.HCENTER_BOTTOM);
//					}
//					else {
//						g.drawShadowString(m_name, Tools.BLACK, Tools.RED, m_posX - camX, m_posY - camY + m_activeBox[1], Tools.HCENTER_BOTTOM);
//					}
//				}
//
//			}
//			else if (m_type == GameActorConstants.ACTOR_TYPE_MONSTER) {
//				if (m_status != ACTOR_STATUS_DEAD) {
//					g.drawShadowString(m_name, Tools.BLACK, Tools.RED, m_posX - camX, m_posY - camY + m_activeBox[1], Tools.HCENTER_BOTTOM);
//				}
//			}
//			else if (m_type == GameActorConstants.ACTOR_TYPE_GATHERING) {
//				g.drawShadowString(m_name, Tools.BLACK, Tools.YELLOW, m_posX - camX, m_posY - camY + m_activeBox[1], Tools.HCENTER_BOTTOM);
//			}
//			else if (m_type == GameActorConstants.ACTOR_TYPE_RELIVE) {
//				g.drawShadowString(m_name, Tools.BLACK, Tools.YELLOW, m_posX - camX, m_posY - camY + m_activeBox[1], Tools.HCENTER_BOTTOM);
//			}
		}
	}
	
	public void petlogic(int x,int y){
		super.logic();
		boolean flag = false;
		int w = GameActorConstants.PET_OPENFLEX_DISTANCE;
		int sx = x - w;
		int px = x + w;
		int sy = y - w;
		int py = y + w;
		if(m_posX > sx 
			&& m_posX < px
			&& m_posY > sy
			&& m_posY < py){
			flag = true;
		}
		if(!flag){
			Point p = new Point(x, y);
//			Tools.debugPrintln("x="+x+";y="+y);
			if(m_flexBuffer != null){
				m_flexBuffer.clear();
				m_flexBuffer.add(p);
			}
			p = null;
		}
	}

	public void logic()
	{

		super.logic();

		if (m_type == GameActorConstants.ACTOR_TYPE_GATE) {
			logic_gate();
		}

		switch (m_actionIDNow / DIRECT_NUM) {
			case ACTION_ATTACK1:
			case ACTION_ATTACK2:
				if (m_actionOver && !m_actionCycle) {
					setAction(ACTION_STAND * DIRECT_NUM + m_direct, 0, 0, true, false);
				}
				break;
			case ACTION_DEAD:
				if (m_actionOver && !m_actionCycle) {
					if (isDead()) {
						deactivate();
					}
					setAction(ACTION_STAND * DIRECT_NUM + m_direct, 0, 0, true, false);
				}
				return;
		}
	}

	public void logic_gate()
	{
		if (DWGameManager.getInstance().m_role.m_pathfinding_start && !DWGameManager.getInstance().m_role.m_pathfinding_pause) {
			return;
		}
		if(UIHook.s_autoHook){
			return;
		}
		if (collide(m_scene.m_controlledActor, true) && !collidePreFrame(m_scene.m_controlledActor, true)) {
			// 弹出切换框
			final DWMessageBox messageBox = new DWMessageBox("", "确认去" + m_name + "?");
			messageBox.addListener(new DWListener() {

				public void OnDoubleClick()
				{

				}

				public void OnClick()
				{
					if (DWMessageBox.SOFTKEY_OK == messageBox.getResult()) {
						DWGameManager.getInstance().getSendMessage().sendChange(m_gameId);
						DWControlsManager.getInstance().removeControl(messageBox);
					}
					else if (DWMessageBox.SOFTKEY_BACK == messageBox.getResult()) {
						DWControlsManager.getInstance().removeControl(messageBox);
					}

				}
			});
			DWControlsManager.getInstance().addControl(messageBox);
			// 设置角色站立
			m_scene.m_controlledActor.stay(DWGameManager.getInstance().m_role.m_direct);
		}

	}

	/**
	 * 角色是否能移动
	 * 
	 * @return
	 */
	public boolean canMove()
	{
		if (m_curCombatSkill == null)
			return true;
		if (!m_curCombatSkill.isActive())
			return true;
		switch (m_curCombatSkill.getCurStep()) {
			case SkillConstants.阶段_施法:
				return false;
			default:
				return true;
		}
	}

	public void updateMove()
	{
		switch (m_actionIDNow / DIRECT_NUM) {
			default:
				return;
			case ACTION_STAND:
			case ACTION_MOVE:
				break;
		}
		super.updateMove();
	}

	public void dispose()
	{
		super.dispose();
		m_relatedActorsID = null;
	}

	public int doAction(Object data)
	{
		return 0;
	}
	
	public void dealDead()
	{
		if (m_status != ACTOR_STATUS_DEAD)
			return;
		if (!m_enabled || m_actionIDNow / GameActorConstants.DIRECT_NUM == ACTION_DEAD)
			return;
		super.dealDead();
		if (m_flexBuffer.isEmpty() && m_vX == 0 && m_vY == 0) {
			setAction(ACTION_DEAD * GameActorConstants.DIRECT_NUM + m_direct, false, false);
		}
	}
	
	@Override
	public boolean isDead()
	{
		return m_status == Npc.ACTOR_STATUS_DEAD;
	}
	
	////////////////////////////////////////////////////////////
	//// 同屏相关
	public void recvSceneAdd(DataInputStream dis)
	{
		try {
			m_faction = dis.readByte();
			m_actor_flag = dis.readByte();
			m_vocation = dis.readByte();
			m_sex = dis.readByte();
			m_name = dis.readUTF();
			m_lv = dis.readShort();
			m_status = dis.readByte();
			m_action = dis.readInt();
			m_underAttack_range = dis.readShort();
			m_hp = dis.readInt();
			m_hpMax = dis.readInt();
			m_mp = dis.readInt();
			m_mpMax = dis.readInt();
			
			int resCount = dis.readByte();// 资源个数
			if (m_refsResHead == null) {
				m_refsResHead = new ResHead[resCount];
			}
			if (m_anims == null) {
				m_anims = new Animation[resCount];
			}
			
			String[] urls = new String[resCount];
			String temp;
			for (int j = 0; j < resCount; j++) {
				temp = dis.readUTF();
				if (temp.length() == 0) {
					temp = null;
				}
				urls[j] = temp;
			}
			
			int speed = dis.readShort();
			setAttr(Attribute.SPEED, speed);
			m_velocity = speed / (float) DWGameManager.FRAME_PER_SECOND;
			m_posX = dis.readShort();
			m_posY = dis.readShort();
			
			m_actionIDNow = dis.readShort(); 
			
			if (m_type == GameActorConstants.ACTOR_TYPE_PET) {
				m_collideBox[0] = -30;
				m_collideBox[1] = -13;
				m_collideBox[2] = 30;
				m_collideBox[3] = 13;
				m_activeBox[0] = -30;
				m_activeBox[1] = -90;
				m_activeBox[2] = 30;
				m_activeBox[3] = 10;
				for (int i = 0; i < resCount; i++) {
					m_refsResHead[i] = new ResHead();
					m_refsResHead[i].m_type = DWSerializableFactory.RESOURCE_TYPE_ANIM;// 读取动画资源类型
					m_refsResHead[i].m_url = new StringBuffer(DWSerializableFactory.DIR_ANIM).append(urls[i])
							.append(DWSerializableFactory.EXTENSION_ANIM).toString();// 读取动画资源URL
					m_refsResHead[i].m_version = 1;// 读取动画资源版本
					m_anims[i] = (Animation) (ResourceManager.getInstance().loadResource(DWGameManager
							.getInstance().m_resourceDynamic, m_refsResHead[i]));
				}
			}
			else {
				ResHead head = new ResHead();
				head.m_type = DWSerializableFactory.RESOURCE_TYPE_NPC;
				head.m_url = new StringBuffer(DWSerializableFactory.DIR_AC).append(urls[0]).append(
						DWSerializableFactory.EXTENSION_AC).toString();// 读取角色动画资源URL
				head.m_version = 1;
				Npc model = (Npc) ResourceManager.getInstance().loadResource(
						DWGameManager.getInstance().m_resourceDynamic, head);
				if (model != null) {
					copy(model);
				}
				else {
					Tools.debugPrintln("场景文件中缺失NPC数据： NPC url = " + head.m_url);
					return;
				}
			}

			m_anim = m_anims[0];
			
			clearFlex();
			
			activate();
			
			if (m_status == Npc.ACTOR_STATUS_DEAD) {
				setAction(Npc.ACTION_DEAD * Npc.DIRECT_NUM, 0, 0, false, true);
				setFrame(m_anim.m_actions[Npc.ACTION_DEAD * Npc.DIRECT_NUM].length - 1);
			}
			else {
				setAction(m_actionIDNow, true);
			}
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}
	
	public void recvSceneUpdatePosition(DataInputStream dis)
	{
		try {
			short x = dis.readShort();
			short y = dis.readShort();
			activate();
			addFlex(new Point(x, y));
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}
	
	public void recvSceneUpdateData(DataInputStream dis)
	{
		try {
			m_hp = dis.readInt();
			m_hpMax = dis.readInt();
			m_mp = dis.readInt();
			m_mpMax = dis.readInt();
			
			setAttr(Attribute.MAX_HP, m_hpMax);
			setAttr(Attribute.MAX_MP, m_mpMax);
			
			//更新自身头像以及目标头像
			if (this == m_scene.m_controlledActor.m_targetActor) {
				UIWindows.getMain().updateTargetHead();
			}
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}
	
	public void recvSceneUpdateFigure(DataInputStream dis)
	{
		try {
			int resCount = dis.readByte();// 读资源个数
			String[] urls = new String[resCount];
			String temp;

			for (int j = 0; j < resCount; j++) {
				temp = dis.readUTF();
				if (temp.length() == 0) {
					temp = null;
				}
				urls[j] = temp;// 动画URL
			}
			
			int speed = dis.readShort();
			setAttr(Attribute.SPEED, speed);
			m_velocity = speed / (float) DWGameManager.FRAME_PER_SECOND;
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}
	
	public void recvSceneUpdateStatus(DataInputStream dis)
	{
		try {
			m_status = dis.readByte();
			if (isDead()) {
				dealDead();
				if (this == m_scene.m_controlledActor.m_targetActor) {
					m_scene.setTargetActor(null);
					m_scene.m_controlledActor.clearAutoAttack();
				}
			}
			else {
				stay(m_direct);
			}
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}
	
	public void recvSceneUpdateAction(DataInputStream dis)
	{
		try {
			m_action = dis.readInt();
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}
	//// 同屏相关
	////////////////////////////////////////////////////////////

	public static final int ACTION_STAND = 0;
	public static final int ACTION_MOVE = 1;
	public static final int ACTION_DEAD = 2;
	public static final int ACTION_ATTACK1 = 3;
	public static final int ACTION_ATTACK2 = 4;
	
	// 状态
	public static final int ACTOR_STATUS_FREE = 0;//自由状态
	public static final int ACTOR_STATUS_DEAD = 11;//死亡状态
}
